import json
import copy
from apis import api_routes
from flask import g, jsonify
from models.users.roles import Roles
from models.users.users import Users
from security.decoration import certification
from security.security import decode_jwt
from public.sidebar import sidebars
from typing import List


@api_routes.route("/sidebar", methods=["GET"])
@certification(auth=True, role=None)
def func_sidebar_get_api():
    """
    根据角色返回角色可以操作哪些页面
    http://127.0.0.1:8080/api/sidebar
    Content-Type=application/x-www-form-urlencoded
    methods=["GET"]
    :return:
        {'status': 40000, 'msg': "根据role_id没有找到角色"}
    ---
    tags:
      - MES侧边栏数据查看
    """
    user: Users = g.session.query(Users).filter(Users.id == decode_jwt(g.token)["user_id"]).first()
    role: Roles = g.session.query(Roles).filter(Roles.id == user.role_id).first()

    db_sidebar: dict = json.loads(role.sidebars) if (role.sidebars is not None) else {}
    sidebar = copy.deepcopy(sidebars)

    if role.role == "admin":
        for index0, itr0 in enumerate(sidebar):
            itr0["allow"] = True
            children: List[dict] = itr0.get("children")
            for index00, itr00 in enumerate(children):
                itr00["allow"] = True
    else:
        for index1, itr1 in enumerate(sidebar):
            mark1 = itr1.get("mark")
            children: list = itr1.get("children")

            if len(children) == 0:
                db_mark: [bool, None] = db_sidebar.get(mark1)
                if db_mark is not None and db_mark is True:
                    itr1["allow"] = True

            new_children: list = copy.deepcopy(children)
            children.clear()

            for index11, itr11 in enumerate(new_children):
                mark11 = itr11.get("mark")
                db_mark: [bool, None] = db_sidebar.get(mark11)

                if db_mark is not None and db_mark is True:
                    itr1["allow"] = True
                    itr11["allow"] = True
                    children.append(copy.deepcopy(itr11))

        temp = copy.deepcopy(sidebar)
        sidebar.clear()
        for xxx in temp:
            if xxx.get("allow"):
                sidebar.append(xxx)

    return jsonify({'status': 200, 'data': sidebar})
